package ae.whereamihurt.client.event;

import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.particles.ParticleTypes;
import net.minecraft.util.DamageSource;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.world.World;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.event.entity.living.LivingDamageEvent;
import net.minecraftforge.event.entity.living.LivingEntityUseItemEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

import static ae.whereamihurt.lib.util.Constants.ID_MOD;
import static net.minecraft.particles.ParticleTypes.EXPLOSION;

@Mod.EventBusSubscriber(modid = ID_MOD)
public class LivingDamageEvents {

    @SubscribeEvent
    public static void livingDamageEvent(LivingDamageEvent event) {
        LivingEntity entityLiving = event.getEntityLiving();
        World world = entityLiving.world;
        if (!world.isRemote) {
            if (!(entityLiving instanceof PlayerEntity)) {
                return;
            }

            PlayerEntity player = (PlayerEntity) entityLiving;
            DamageSource source = event.getSource();
            Entity immediateSource = source.getImmediateSource();

            if (immediateSource == null) {
                return;
            }

            AxisAlignedBB box = player.getPoseAABB(player.getPose());

            Vector3d lookVec = immediateSource.getLookVec();
            Vector3d eyePosition = immediateSource.getEyePosition(1);
//        Vector3d lookEnd = new Vector3d(lookVec.x, lookVec.y, lookVec.z).scale(10d);//十格的距离
//        BlockRayTraceResult trace = AxisAlignedBB.rayTrace(Collections.singletonList(box), lookVec, lookEnd, player.getPosition());
//
//        if (trace == null) {
//            //出现null的可能原因，范围攻击
//            return;
//        }
//
//        Vector3d hitVec = trace.getHitVec();
//        world.addParticle(REDSTONE_DUST, hitVec.x, hitVec.y, hitVec.z, 0d, 0d, 0d);

            ((ServerWorld)world).spawnParticle(ParticleTypes.HEART, eyePosition.x, eyePosition.y, eyePosition.z, 1, 0d, 0d, 0d, 0d);//能否让粒子效果跟随玩家？
        }
    }

    @SubscribeEvent
    public static void test(LivingEntityUseItemEvent event) {
        LivingEntity entity = event.getEntityLiving();
        World world = entity.world;
        if (!world.isRemote)
            entity.world.addParticle(EXPLOSION, entity.getPosX(), entity.getPosY(), entity.getPosZ(), 0d, 0d, 0d);
//        System.out.println(event.getEntityLiving().getPose());
    }
}
